import logging
from django_redis import get_redis_connection
from redis import RedisError
from rest_framework import serializers


class ImageCodeCheckSerializer(serializers.Serializer):
    image_code_id = serializers.UUIDField()
    text = serializers.CharField(max_length=4, min_length=4)
    # 为什么mobile不校验

    def validate(self, attrs):
        # UUID
        image_code_id = attrs['image_code_id']
        # 用户输入的图片验证码内容
        text = attrs['text']

        redis_conn = get_redis_connection("verify_codes")
        #获取真实图片验证码内容
        real_image_code_text = redis_conn.get("img_%s" %image_code_id)
        if not real_image_code_text:
            raise serializers.ValidationError('图片验证码无效')

        # 获取之后及时删除redis中图片严重码内容(优化1)
        # 这里如果不使用try-excetp捕获异常，drf将使用utils模块中自定义的异常，中断程序执行，导致后面的操作无法继续
        # 日志记录器
        logger = logging.getLogger('django')
        try:
            redis_conn.delete('verify_codes')
        except RedisError as e:
            logger.error(e)

        real_image_code_text = real_image_code_text.decode()
        if real_image_code_text.lower() != text.lower():
            raise serializers.ValidationError('图片验证码错误')

        # 判断是否在60秒内频繁发送(优化2)
        mobile = self.context['view'].kwargs['mobile']
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            raise serializers.ValidationError('发送短信验证码过于频繁')

        return attrs























